package com.lxm.ymcc.exlipus;


import com.lxm.ymcc.eums.YmccSystemError;
import com.lxm.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public JSONResult globalException(HttpServletResponse response, Exception ex){

        ex.printStackTrace();
        log.info("GlobalExceptionHandler...");
        log.info("错误代码："  + response.getStatus());

        return JSONResult.error(YmccSystemError.DB_SERVICE_ERROR);
}

    @ResponseBody
    @ExceptionHandler(GlobalException.class)
    public JSONResult balExcept(HttpServletResponse response, GlobalException ex){

        ex.printStackTrace();
        log.info("GlobalExceptionHandler...");
        log.info("错误代码："  + response.getStatus());

        return JSONResult.error(ex.getMessage(),"-2");
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult saveException(HttpServletResponse response, MethodArgumentNotValidException ex){

        ex.printStackTrace();
        log.info("GlobalExceptionHandler...");
        log.info("错误代码："  + response.getStatus());
        StringBuilder sb = new StringBuilder("数据格式:");

        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        for (ObjectError allError : allErrors) {
            sb.append(allError.getDefaultMessage()).append(";");

        }
        return JSONResult.error(sb.toString(),"20220");
    }

}